import request from '@/utils/request'
import type {
  WorkRecord,
  WorkCategory,
  CreateWorkRecordRequest,
  UpdateWorkRecordRequest,
  GenerateReportRequest,
  GeneratedReportResponse,
  WorkRecordQueryParams,
  PageResponse,
  GeneratedReport,
  ReportQueryRequest,
  ReportUpdateRequest,
  BatchOperationRequest,
  ReportStats
} from '@/types/workReport'

/**
 * 工作报告相关API
 */

// ==================== 工作分类 API ====================

/**
 * 获取用户的所有分类（包括系统分类）
 */
export const getUserCategories = (): Promise<WorkCategory[]> => {
  return request.get('/work-reports/categories')
}

/**
 * 获取系统分类
 */
export const getSystemCategories = (): Promise<WorkCategory[]> => {
  return request.get('/work-reports/categories/system')
}

/**
 * 创建用户自定义分类
 */
export const createCategory = (data: {
  name: string
  description?: string
  color?: string
  icon?: string
}): Promise<WorkCategory> => {
  const params = new URLSearchParams()
  params.append('name', data.name)
  if (data.description) params.append('description', data.description)
  if (data.color) params.append('color', data.color)
  if (data.icon) params.append('icon', data.icon)
  
  return request.post('/work-reports/categories', params, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

/**
 * 更新用户自定义分类
 */
export const updateCategory = (categoryId: number, data: {
  name?: string
  description?: string
  color?: string
  icon?: string
}): Promise<WorkCategory> => {
  const params = new URLSearchParams()
  if (data.name) params.append('name', data.name)
  if (data.description) params.append('description', data.description)
  if (data.color) params.append('color', data.color)
  if (data.icon) params.append('icon', data.icon)

  return request.put(`/work-reports/categories/${categoryId}`, params, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

/**
 * 删除用户自定义分类
 */
export const deleteCategory = (categoryId: number): Promise<void> => {
  return request.delete(`/work-reports/categories/${categoryId}`)
}

/**
 * 获取分类详情
 */
export const getCategoryById = (categoryId: number): Promise<WorkCategory> => {
  return request.get(`/work-reports/categories/${categoryId}`)
}

// ==================== 工作记录 API ====================

/**
 * 创建工作记录
 */
export const createWorkRecord = (data: CreateWorkRecordRequest): Promise<WorkRecord> => {
  return request.post('/work-reports/records', data)
}

/**
 * 更新工作记录
 */
export const updateWorkRecord = (recordId: number, data: UpdateWorkRecordRequest): Promise<WorkRecord> => {
  return request.put(`/work-reports/records/${recordId}`, data)
}

/**
 * 删除工作记录
 */
export const deleteWorkRecord = (recordId: number): Promise<void> => {
  return request.delete(`/work-reports/records/${recordId}`)
}

/**
 * 获取工作记录详情
 */
export const getWorkRecord = (recordId: number): Promise<WorkRecord> => {
  return request.get(`/work-reports/records/${recordId}`)
}

/**
 * 分页查询用户的工作记录
 */
export const getUserWorkRecords = (params: WorkRecordQueryParams = {}): Promise<PageResponse<WorkRecord>> => {
  return request.get('/work-reports/records', { params })
}

/**
 * 根据日期查询工作记录
 */
export const getWorkRecordsByDate = (date: string): Promise<WorkRecord[]> => {
  return request.get('/work-reports/records/by-date', {
    params: { date }
  })
}

/**
 * 根据日期范围查询工作记录
 */
export const getWorkRecordsByDateRange = (startDate: string, endDate: string): Promise<WorkRecord[]> => {
  return request.get('/work-reports/records/by-date-range', {
    params: { startDate, endDate }
  })
}

// ==================== 报告生成 API ====================

/**
 * 生成工作报告
 */
export const generateReport = (data: GenerateReportRequest): Promise<GeneratedReportResponse> => {
  return request.post('/work-reports/generate', data, {
    timeout: 120000 // 120秒超时，适合AI生成操作（GLM-4.1V-9B-Thinking模型需要更长时间）
  })
}

/**
 * 快速生成今日日报
 */
export const generateTodayReport = (settings?: {
  model?: string
  temperature?: number
  maxLength?: number
  style?: string
  includeContent?: string[]
}): Promise<GeneratedReportResponse> => {
  return request.post('/work-reports/generate/daily', settings || {}, {
    timeout: 120000 // 120秒超时，适合AI生成操作
  })
}

/**
 * 快速生成本周周报
 */
export const generateThisWeekReport = (): Promise<GeneratedReportResponse> => {
  return request.post('/work-reports/generate/weekly', {}, {
    timeout: 120000 // 120秒超时，适合AI生成操作
  })
}

/**
 * 快速生成本月月报
 */
export const generateThisMonthReport = (): Promise<GeneratedReportResponse> => {
  return request.post('/work-reports/generate/monthly', {}, {
    timeout: 120000 // 120秒超时，适合AI生成操作
  })
}

/**
 * 生成指定日期的日报
 */
export const generateDailyReportByDate = (date: string): Promise<GeneratedReportResponse> => {
  return request.post(`/work-reports/generate/daily/${date}`, {}, {
    timeout: 120000 // 120秒超时，适合AI生成操作
  })
}

/**
 * 保存报告到历史记录
 */
export const saveReportToHistory = (data: {
  type: string
  startDate: string
  endDate: string
  content: string
  title?: string
}): Promise<number> => {
  return request.post('/work-reports/save', data)
}

// ==================== 工具函数 ====================

/**
 * 格式化时间显示
 */
export const formatTimeSpent = (minutes: number): string => {
  if (minutes < 60) {
    return `${minutes}分钟`
  }
  const hours = Math.floor(minutes / 60)
  const remainingMinutes = minutes % 60
  if (remainingMinutes === 0) {
    return `${hours}小时`
  }
  return `${hours}小时${remainingMinutes}分钟`
}

/**
 * 获取状态颜色
 */
export const getStatusColor = (status: string): string => {
  const statusMap: Record<string, string> = {
    'PENDING': '#909399',
    'IN_PROGRESS': '#409EFF',
    'COMPLETED': '#67C23A',
    'CANCELLED': '#F56C6C'
  }
  return statusMap[status] || '#909399'
}

/**
 * 获取优先级颜色
 */
export const getPriorityColor = (priority: string): string => {
  const priorityMap: Record<string, string> = {
    'LOW': '#909399',
    'MEDIUM': '#409EFF',
    'HIGH': '#E6A23C',
    'URGENT': '#F56C6C'
  }
  return priorityMap[priority] || '#409EFF'
}

// ==================== 报告管理 API ====================

/**
 * 获取报告列表（分页、筛选、搜索）
 */
export const getReportList = (params: ReportQueryRequest): Promise<PageResponse<GeneratedReport>> => {
  return request.get('/work-reports/manage/reports', { params })
}

/**
 * 获取报告详情
 */
export const getReportDetail = (reportId: number): Promise<GeneratedReport> => {
  return request.get(`/work-reports/manage/reports/${reportId}`)
}

/**
 * 更新报告
 */
export const updateReport = (reportId: number, data: ReportUpdateRequest): Promise<GeneratedReport> => {
  return request.put(`/work-reports/manage/reports/${reportId}`, data)
}

/**
 * 删除报告
 */
export const deleteReport = (reportId: number): Promise<void> => {
  return request.delete(`/work-reports/manage/reports/${reportId}`)
}

/**
 * 批量删除报告
 */
export const batchDeleteReports = (data: BatchOperationRequest): Promise<void> => {
  return request.post('/work-reports/manage/reports/batch-delete', data)
}

/**
 * 获取报告统计信息
 */
export const getReportStats = (): Promise<ReportStats> => {
  return request.get('/work-reports/manage/stats')
}

/**
 * 获取工作记录分类统计
 */
export const getCategoryStats = (): Promise<Record<string, number>> => {
  return request.get('/work-statistics/category-summary')
}

/**
 * 导出报告
 */
export const exportReport = (reportId: number, format: string, includeOriginal = false): Promise<string> => {
  return request.get(`/work-reports/manage/reports/${reportId}/export`, {
    params: { format, includeOriginal }
  })
}
